// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const { id } = event
  
  if (!id) {
    return {
      success: false,
      errMsg: '缺少套餐ID'
    }
  }
  
  try {
    // 查询套餐基本信息
    const bundleResult = await db.collection('bundles').doc(id).get()
    const bundle = bundleResult.data
    
    if (!bundle) {
      return {
        success: false,
        errMsg: '套餐不存在'
      }
    }
    
    // 查询套餐分组信息
    const groupsResult = await db.collection('bundleGroups')
      .where({
        bundleId: id
      })
      .orderBy('order', 'asc')
      .get()
    
    const groups = groupsResult.data
    
    // 查询分组商品信息
    const groupIds = groups.map(group => group._id)
    const itemsResult = await db.collection('bundleItems')
      .where({
        groupId: db.command.in(groupIds)
      })
      .orderBy('order', 'asc')
      .get()
    
    const items = itemsResult.data
    
    // 组装完整套餐数据
    const bundleData = {
      ...bundle,
      groups: groups.map(group => ({
        ...group,
        items: items.filter(item => item.groupId === group._id)
      }))
    }
    
    return {
      success: true,
      data: bundleData
    }
  } catch (err) {
    console.error('获取套餐详情失败', err)
    return {
      success: false,
      errMsg: '获取套餐详情失败'
    }
  }
}